import { iServerHttp,meterToDegree } from '@/map/projMap.js';
import {FeatureService, GetFeaturesByGeometryParameters} from "@supermap/iclient-ol";
import Circle from 'ol/geom/Circle';
import {fromCircle} from 'ol/geom/Polygon';

//根据经纬度空间查询图层数据
export async function queryFeatureByLonLat(databaseName, tableName, lonlat, dataTypeInfo, sql, zoom, fields){
    return new Promise(async (resolve, reject) => {
        let datasource = databaseName;
        let dataset = tableName;
        let temp = Math.pow(2,(18 - zoom));//根据地图缩放设置系数
        //点生成圆多边形
        let meter = 3 * temp;//米
        let degree = meterToDegree(meter);
        let circle = new Circle(lonlat, degree); // 用圆心和半径确定一个圆
        let polygon = new fromCircle(circle); // 得到一个多边形
        //几何查询
        let resultArray = await queryFeatureByGeometry(datasource,dataset,polygon,dataTypeInfo,sql,fields);
        //[dataTypeInfo,主键id,查询结果feature]
        resolve(resultArray);
    });
}

export function queryFeatureByGeometry(datasource, dataset, geometry, dataTypeInfo, sql, fields){//几何查询
    return new Promise((resolve, reject) => {
        //let url = "http://10.13.155.192:8090/iserver/services/data-fxfzdzzh/rest/data";
        let url = iServerHttp() + "/iserver/services/data-"+datasource+"/rest/data";
        let geometryParam = new GetFeaturesByGeometryParameters({
            datasetNames: [datasource+":"+dataset],
            geometry: geometry,
            spatialQueryMode: "INTERSECT",
            attributeFilter:sql,//查询过滤条件
        });
        if(fields!=null && fields.length>0){
            geometryParam = new GetFeaturesByGeometryParameters({
                datasetNames: [datasource+":"+dataset],
                geometry: geometry,
                spatialQueryMode: "INTERSECT",
                attributeFilter:sql,//查询过滤条件
                fields:fields,//属性字段只包含所指定的字段。不设置即返回全部字段
            });
        }
        new FeatureService(url).getFeaturesByGeometry(geometryParam, function (serviceResult) {
            console.log("dataset"+dataset);
            console.log(serviceResult.result);
            let resultArray = [dataTypeInfo,null,null];
            if(serviceResult.result){
                let features = serviceResult.result.features.features;
                if(features && features.length>0){
                    console.log(features);
                    console.log(features[0].properties);
                    let fieldId = dataTypeInfo.fieldId.toUpperCase();//主键ID字段名
                    //主键ID
                    let id = features[0].properties[fieldId];
                    resultArray = [dataTypeInfo,id,features[0]];
                }
            }
            resolve(resultArray);
        });
    });
}